﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.SessionState;
using System.Web.UI.WebControls;
using GWEB.WebBase.Data;
using GWEB.WebBase.Entity;
using GWEB.WebBase.Utility;
using GWEB.WebFrame.Public;
using Newtonsoft.Json;

namespace GWEB.WebFrame.Activitys
{
    public class ActivityController : PageInfoBase
    {
        [ActionFilter(IsLogin = false)]
        public ActionResult Index(String id, String keyCode)
        {
            return Load("Activity", "Activitys/Activity", id, keyCode);
        }
        [ActionFilter(IsLogin = false)]
        public JsonResult UpdateState(String id, String keyCode, String state)
        {
            if (!Fun.IDVerify(id, keyCode))
                return BasePage.Json(ResultData.Code("0001", "您没有权限"));

            BaseData bd = new BaseData();
            string UserId = BasePage.GetUserId(Session);
            String sql = "update cu_Activity set state={0},auditingid='" + UserId + "',auditingdate='" + System.DateTime.Now.ToString() + "' where id={1}";


            bool t = bd.ExecuteSQL(string.Format(sql, state, id));
            if (t)
                return BasePage.Json(ResultData.Code("0000", WebMessage.SaveSuccess));
            else
                return BasePage.Json(ResultData.Code("0001", WebMessage.SaveFailure));
        }

        public JsonResult DelActivity(String id, String keyCode)
        {
            if (!Fun.IDVerify(id, keyCode))
                return BasePage.Json(ResultData.Code("0001", "您没有权限"));

            BaseData bd = new BaseData();
            string UserId = BasePage.GetUserId(Session);
            String sql = "delete cu_Activity where id={0}";


            bool t = bd.ExecuteSQL(string.Format(sql, id));
            if (t)
                return BasePage.Json(ResultData.Code("0000", WebMessage.SaveSuccess));
            else
                return BasePage.Json(ResultData.Code("0001", WebMessage.SaveFailure));
        }
        [ActionFilter(IsLogin = false)]
        public JsonResult Downline(String id, String keyCode, int type)
        {
            if (!Fun.IDVerify(id, keyCode))
                return BasePage.Json(ResultData.Code("0001", "您没有权限"));

            BaseData bd = new BaseData();
            string UserId = BasePage.GetUserId(Session);
            String sql = "update cu_Activity set state={0} where id={1}";
            bool t = bd.ExecuteSQL(string.Format(sql, type, id));
            if (t)
                return BasePage.Json(ResultData.Code("0000", WebMessage.SaveSuccess));
            else
                return BasePage.Json(ResultData.Code("0001", WebMessage.SaveFailure));
        }
        [ActionFilter(IsLogin = false)]
        public JsonResult Used(String id, String keyCode)
        {
            if (!Fun.IDVerify(id, keyCode))
                return BasePage.Json(ResultData.Code("0001", "您没有权限"));
            BaseData bd = new BaseData();
            String sql = "update cu_Activity set used={0} where id={1}";
            bool t = bd.ExecuteSQL(string.Format(sql, 1, id));
            if (t)
                return BasePage.Json(ResultData.Code("0000", WebMessage.SaveSuccess));
            else
                return BasePage.Json(ResultData.Code("0001", WebMessage.SaveFailure));
        }
        [ActionFilter(IsLogin = false)]
        [HttpPost]
        public ActionResult Upload(string DirName)
        {
            #region + 变量
            //文件大小（字节数）
            long fileSize = 0;
            //重命名的文件名称
            string tempName = "";
            //物理路径+重命名的文件名称
            string fileName = "";
            //文件扩展名
            string extname = "";
            //虚拟路径
            string dir = "/UpFile/" + DirName;
            string path = HostingEnvironment.MapPath(dir);


            //获取提交的文件
            var file = Request.Files[0];
            //反馈对象     



            string _response = "{\"code\": 1,\"msg\": \"服务器故障\",\"data\": {\"src\": \"\"}}"; ;
            #endregion
            #region + 服务器本地文件上传处理
            try
            {
                if (file != null && !string.IsNullOrEmpty(file.FileName))
                {
                    dir = DateTime.Now.ToString("yyyy-MM-dd");
                    if (!Directory.Exists(path + dir))
                    {
                        Directory.CreateDirectory(path + dir);
                    }
                    extname = file.FileName.Substring(file.FileName.LastIndexOf('.'), (file.FileName.Length - file.FileName.LastIndexOf('.')));
                    tempName = Guid.NewGuid().ToString().Substring(0, 6) + extname;
                    fileName = path + dir + "/" + tempName;
                    fileSize += file.ContentLength;
                    using (FileStream fs = System.IO.File.Create(fileName))
                    {
                        file.InputStream.CopyTo(fs);
                        fs.Flush();
                    }
                    _response = "{\"code\": 0,\"msg\": \"服务器本地上传成功\",\"data\": {\"src\": \"" + dir + "/" + tempName + "\"}}";

                }
            }
            catch (Exception ex)
            {

                _response = "{\"code\": 2,\"msg\": \"服务器本地上传失败 / n" + "错误信息：" + ex.Message + "\",\"data\": {\"src\": \"\"}}";
            }
            #endregion
            return Json(_response);
        }
        [ActionFilter(IsLogin = false)]
        [HttpGet]
        public ActionResult DownFile(string filePath, string fileName)
        {
            try
            {


                // filePath 文件路径 例如：/File/记录.xlsx 
                // fileName 文件名称 例如：记录.xlsx （要后缀哦）
                Encoding encoding; // 申明编码
                string outputFileName; // 输出名字
                Debug.Assert(HttpContext.ApplicationInstance.Request.UserAgent != null, "HttpContext.ApplicationInstance.Request.UserAgent != null");
                string browser = HttpContext.ApplicationInstance.Request.UserAgent.ToUpper();
                //微软的浏览器和ie过滤
                if (browser.Contains("MS") && browser.Contains("IE"))
                {
                    outputFileName = HttpUtility.UrlEncode(filePath);
                    encoding = Encoding.Default;
                }
                //火狐
                else if (browser.Contains("FIREFOX"))
                {
                    outputFileName = fileName;
                    encoding = Encoding.GetEncoding("GB2312");
                }
                else
                {
                    outputFileName = HttpUtility.UrlEncode(fileName);
                    encoding = Encoding.Default;
                }
                string absoluFilePath = Server.MapPath(filePath); //获取上传文件路径
                FileStream fs = new FileStream(absoluFilePath, FileMode.Open);
                byte[] bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close(); //关闭流，释放资源
                HttpContext.ApplicationInstance.Response.Clear();
                HttpContext.ApplicationInstance.Response.Buffer = true;
                HttpContext.ApplicationInstance.Response.ContentEncoding = encoding;
                HttpContext.ApplicationInstance.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", string.IsNullOrEmpty(outputFileName) ? DateTime.Now.ToString("yyyyMMddHHmmssfff") : outputFileName));
                Response.BinaryWrite(bytes);
                Response.Flush();
                HttpContext.ApplicationInstance.Response.End();
            }
            catch (Exception Ex)
            {
                return BasePage.Json(ResultData.Code("0009", "" + Ex));
                throw;
            }
            return BasePage.Json(ResultData.Code("0001", "下载成功！"));
        }
        protected override void FieldAddInit(DataRow data)
        {
            //data["CreateId"] = BasePage.GetUserId(Session);
            data["LeagueId"] = 1;
            ViewBag.Lx = 0;
            data["state"] = 1;
            data["SignNumber"] = 0;
            data["chargeId"] = 1;
            data["ActType"] = 0;
            data["NoMPrice"] = 0;
            data["Classhour"] = 0;
            data["used"] = 0;
            data["MPrice"] = 0;
            data["Createdate"] = DateTime.Now.ToString();
            base.FieldAddInit(data);
        }
        protected override void FieldEditInit(DataRow data)
        {
            ViewBag.Lx = 1;
            base.FieldEditInit(data);
        }

    }
}